package com.hst.capacity.application.mail.impl;

import com.hst.capacity.application.mail.MailService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

@Service
public class MailServiceImpl implements MailService {

    @Value("${spring.mail.host}")
    private String host;
    @Value("${spring.mail.port}")
    private int port;
    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    private static final JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

    public void configureMailSenderWithProxy() {
        // 设置代理服务器的地址和端口
        this.mailSender.setHost(this.host);
        this.mailSender.setPort(this.port);

        // 设置代理认证所需的用户名和密码
        this.mailSender.setUsername(this.username);
        this.mailSender.setPassword(this.password);

        // 配置JavaMail的属性
        Properties properties = new Properties();
        properties.put("mail.host", "smtp.qq.com");
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.port", this.port);
        properties.put("mail.smtp.socketFactory.port", this.port);

        this.mailSender.setJavaMailProperties(properties);
    }

    /**
     * 发送邮件
     *
     * @param from 发件人
     * @param to 收件人
     * @param subject 邮件标题
     * @param text 邮件内容
     * @param files 邮件附件
    **/
    public void sendMail(String from, String to, String subject, String text, File[] files) {

        try {

            this.configureMailSenderWithProxy();

            MimeMessage mimeMessage = mailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom(from);
            helper.setTo(to);
            helper.setBcc("23201068@qq.com");
            helper.setSubject(subject);
            helper.setText(text, true);
            if (files != null) {
                for (File file : files) {
                    helper.addAttachment(file.getName(), file);
                }
            }

            this.mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

    }

    public void sendMail(String from, String to, String subject, String text, String[] attachmentURL)  {

        try {

            this.configureMailSenderWithProxy();

            MimeMessage mimeMessage = mailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom(from);
            helper.setTo(to);
            helper.setBcc("limsh_2_14@163.com");
            helper.setSubject(subject);
            helper.setText(text, true);

            try {
                if (attachmentURL != null) {
                    for (String attURL : attachmentURL) {
                        URL url = new URL(attURL);
                        String path = url.getPath();
                        String fileName = path.substring(path.lastIndexOf('/') + 1);

                        URLConnection connection = url.openConnection();
                        connection.connect();

                        // 获取文件的输入流
                        InputStream inputStream = connection.getInputStream();

                        // 将输入流转换为字节数组
                        byte[] byteArray = toByteArray(inputStream);

                        // 创建 ByteArrayResource 对象
                        InputStreamSource inputStreamSource =
                                new ByteArrayResource(byteArray);
                        helper.addAttachment(fileName, inputStreamSource);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            this.mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

    }

    private static byte[] toByteArray(InputStream input) throws IOException {
        try (BufferedInputStream in = new BufferedInputStream(input);
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            return out.toByteArray();
        }
    }

}
